import React, { useEffect, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableData'
import { addproductFabricType, getproductFabricTypeList, statusproductFabricType } from '@/api/goods'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useFabricTypeColumns } from '../columns'
import { ProductFabricTypeVO } from '../types'
import CustomTable from '@/components/CustomTable'
import { EditFormVertical, SearchForm } from '@/components/CustomForm'
import { STATUSBANDOPTIONS, STATUSNUM } from '@/constant'
import { Button, Drawer, Dropdown, message, Space } from 'antd'
import { DownOutlined, PlusOutlined } from '@ant-design/icons'
import { useAppSelector } from '@/store/hooks'
import { useFormAddFabric } from '../useForm'
import PermissionButton from '@/components/PermissionButton'
import { useSearchParams } from 'react-router-dom'
const Index: React.FC = () => {
  const [form] = useForm()
  const [FormAdd] = useForm()
  const [menuItems, setmenuItems] = useState<{ key: string; label: string }[]>([])
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [isDrawModalShow, setisDrawModalShow] = useState<boolean>(false)
  const [isEdit, setIsEdit] = useState(false)
  const [CurrentInfo, setCurrentInfo] = useState<Record<string, any>>({})
  const [ispedding, setispedding] = useState<boolean>(false)
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [query] = useSearchParams()
  const keyword = query.get('keyword') || ''
  const { tableProps, params, setParams, search, reset } = useGetTableData<ProductFabricTypeVO>(
    getproductFabricTypeList,
    {
      form: form,
      defaultFieldsParams: {
        enableStatus: 1,
        keyword,
      },
      immediatelySend: false,
    },
  )
  useEffect(() => {
    const items: { key: string; label: string }[] = []
    if (buttonCodeList.includes('onFabricType')) {
      items.push({
        key: STATUSNUM.OPEN + '',
        label: '启用面种',
      })
    }
    if (buttonCodeList.includes('offFabricType')) {
      items.push({
        key: STATUSNUM.CLOSE + '',
        label: '停用面种',
      })
    }
    setmenuItems(items)
    search({
      ...params,
      enableStatus: 1,
    })
  }, [])
  const onDrawCancel = () => {
    setisDrawModalShow(false)
    FormAdd.resetFields()
  }
  const onConfirm = async (values: any) => {
    setispedding(true)
    const paramsData = {
      ...values,
    }
    if (isEdit) paramsData.fabricTypeId = CurrentInfo.fabricTypeId
    const res = await addproductFabricType(paramsData).finally(() => setispedding(false))
    if (res.code === 200) {
      setIsEdit(false)
      setCurrentInfo({})
      message.success('操作成功')
      onDrawCancel()
      search(params)
    }
  }
  const selectRows = (keys: React.Key[]) => {
    setselectedRowKeys(keys)
  }
  const handleClickMore = async (info: any) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请勾选需要操作的列表数据！')
      return
    }
    const res = await statusproductFabricType({
      fabricTypeIds: selectedRowKeys,
      enableStatus: info.key == STATUSNUM.OPEN ? 1 : 0,
    })
    if (res.code === 200) {
      message.success('操作成功')
      setselectedRowKeys([])
      search(params)
    }
  }
  const onEdit = (info: ProductFabricTypeVO) => {
    FormAdd.setFieldsValue(info)
    setCurrentInfo(info)
    setIsEdit(true)
    setisDrawModalShow(true)
  }
  return (
    <PageContainer className="goods_fabrictype_page">
      <SearchForm
        className="fabrictypeDom"
        params={params}
        form={form}
        searchConfig={[
          {
            name: 'keyword',
            label: '面种',
            type: 'Input',
            placeholder: '请输入面种编码或面种名称',
          },
          { label: '状态', name: 'enableStatus', type: 'Select', option: STATUSBANDOPTIONS },
        ]}
        onFinish={(vals: any) => {
          setselectedRowKeys([])
          search({
            ...vals,
          })
        }}
        onReset={() => {
          setselectedRowKeys([])
          reset()
        }}
        extra={
          <div className="table_extra_flex">
            <PermissionButton
              permission="createFabricType"
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setisDrawModalShow(true)}
            >
              新建面种
            </PermissionButton>
            {menuItems?.length > 0 ? (
              <Dropdown
                placement="bottomLeft"
                menu={{
                  items: menuItems,
                  onClick: handleClickMore,
                }}
              >
                <Button>
                  更多操作
                  <DownOutlined />
                </Button>
              </Dropdown>
            ) : null}
          </div>
        }
      ></SearchForm>
      <CustomTable
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        bordered
        columns={useFabricTypeColumns({ onEdit })}
        {...tableProps}
        rowKey={(rows) => rows.fabricTypeId}
        extraHeight={28}
        isScrollY
        filterDomClassName="fabrictypeDom"
      />
      <Drawer
        title="新建面种"
        open={isDrawModalShow}
        maskClosable
        onClose={onDrawCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onDrawCancel}>取消</Button>
              <Button
                loading={ispedding}
                type="primary"
                onClick={() => FormAdd.validateFields().then((values) => onConfirm(values))}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={useFormAddFabric()}
          form={FormAdd}
          // onValuesChange={(changedValues) => onValuesChange(changedValues, ['seasonName'], FormAdd)}
        />
      </Drawer>
    </PageContainer>
  )
}

export default Index
